import { useState, useEffect } from 'react'

interface MarketData {
  current_price: number
  price_change_24h: number
  price_change_percentage_24h: number
  volume_24h: number
  market_cap: number
  candles: Array<{
    time: string
    open: number
    high: number
    low: number
    close: number
    volume: number
  }>
}

export function useMarketData(symbol: string, timeframe: string) {
  const [marketData, setMarketData] = useState<MarketData | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchMarketData = async () => {
      try {
        setIsLoading(true)
        setError(null)

        // Simulate API call - replace with actual API endpoint
        await new Promise(resolve => setTimeout(resolve, 1000))

        // Mock data generation
        const basePrice = symbol === 'BTC/USDT' ? 45000 : symbol === 'ETH/USDT' ? 2800 : 100
        const volatility = 0.02
        
        const candles = Array.from({ length: 24 }, (_, i) => {
          const time = new Date()
          time.setHours(time.getHours() - (23 - i))
          
          const randomChange = (Math.random() - 0.5) * volatility
          const open = basePrice * (1 + randomChange)
          const close = open * (1 + (Math.random() - 0.5) * 0.01)
          const high = Math.max(open, close) * (1 + Math.random() * 0.005)
          const low = Math.min(open, close) * (1 - Math.random() * 0.005)
          
          return {
            time: time.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }),
            open: Number(open.toFixed(2)),
            high: Number(high.toFixed(2)),
            low: Number(low.toFixed(2)),
            close: Number(close.toFixed(2)),
            volume: Math.floor(Math.random() * 1000 + 500)
          }
        })

        const mockData: MarketData = {
          current_price: candles[candles.length - 1].close,
          price_change_24h: (Math.random() - 0.5) * 1000,
          price_change_percentage_24h: (Math.random() - 0.5) * 10,
          volume_24h: Math.floor(Math.random() * 1000000 + 500000),
          market_cap: basePrice * 19000000,
          candles
        }

        setMarketData(mockData)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to fetch market data')
      } finally {
        setIsLoading(false)
      }
    }

    fetchMarketData()
    
    // Set up polling every 30 seconds
    const interval = setInterval(fetchMarketData, 30000)
    
    return () => clearInterval(interval)
  }, [symbol, timeframe])

  return {
    marketData,
    isLoading,
    error
  }
}
